<template>
    <el-scrollbar>
        <div v-for="item in lists" :key="item.id">
            <div
                :id="`music-item-${item.id}`"
                class="flex bg-page mb-[20px] p-[20px] rounded-[12px] cursor-pointer"
                @click="selectMusic(item)"
            >

                <!-- 生成中 -->
                <template v-if="item.status === 0 || item.status === 1">
                    <div class="flex-1 flex items-center">
                        <div class="w-[75px] h-[75px] flex items-center justify-center rounded-[12px] bg-body">
                            <div class="flex flex-col items-center">
                                <icon
                                    name="el-icon-Refresh"
                                    class="is-loading"
                                    color="var(--el-text-color-regular)"
                                    :size="26"
                                />
                                <span class="text-xs text-tx-secondary mt-2">
                                    {{ item.status === 0 ? '排队中' : '生成中' }}
                                </span>
                            </div>
                        </div>
                        <div class="ml-4 py-2">
                            <div class="text-[16px] font-bold text-tx-regular">{{ item.title }}</div>
                            <div class="text-sm text-tx-secondary mt-2">{{ item.tags || 'default' }}</div>
                        </div>
                    </div>
                    <div class="flex flex-col items-end">
                        <div class="text-tx-disabled">
                            {{ item.create_time }}
                        </div>
                    </div>
                </template>

                <!-- 生成失败 -->
                <template v-else-if="item.status === 3">
                    <div class="flex-1 flex items-center">
                        <div class="w-[75px] h-[75px] flex items-center justify-center rounded-[12px] bg-body">
                            <div class="flex flex-col items-center">
                                <icon
                                    name="el-icon-Warning"
                                    color="var(--el-text-color-regular)"
                                    :size="26"
                                />
                                <span class="text-xs text-tx-secondary mt-2">生成失败</span>
                            </div>
                        </div>
                        <div class="ml-4 py-1.5">
                            <div class="text-[16px] font-bold text-tx-regular">{{ item.title }}</div>
                            <div class="text-sm text-tx-secondary mt-1">{{ item.tags || 'default' }}</div>
                            <div class="text-xs text-error mt-1">失败原因: {{ item.fail_reason || '未知错误' }}</div>
                        </div>
                    </div>
                    <div class="flex flex-col items-end">
                        <div class="text-tx-disabled">
                            {{ item.create_time }}
                        </div>
                        <div class="flex items-center mt-[25px]">
                            <el-tooltip
                                effect="dark"
                                content="删除"
                                placement="bottom"
                            >
                                <div @click.stop="handleDelete(item.code)">
                                    <Icon
                                        class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                        name="el-icon-Delete"
                                        size="18"
                                        color="#556477"
                                    />
                                </div>
                            </el-tooltip>
                        </div>
                    </div>
                </template>

                <!-- 已生成 -->
                <template v-else>
                    <div class="flex-1 flex items-center">
                        <div class="w-[75px] h-[75px] flex items-center justify-center flex-none relative">
                            <el-image
                                v-if="item.cover_url"
                                :src="item.cover_url"
                                class="w-full h-full rounded-[12px]"
                            />
                            <div v-else class="text-tx-secondary">
                                <icon name="el-icon-VideoPlay" :size="45" />
                            </div>
                            <div
                                v-if="currentId == item.id && playing"
                                class="absolute inset-0 flex items-center justify-center text-white"
                            >
                                <icon name="el-icon-VideoPause" :size="20" />
                            </div>
                            <div
                                v-if="currentId == item.id && !playing"
                                class="absolute inset-0 flex items-center justify-center text-white"
                            >
                                <icon name="el-icon-VideoPlay" :size="20" />
                            </div>
                        </div>

                        <div v-if="item.status === 2" class="ml-[20px]">
                            <div
                                class="text-[16px] font-bold"
                                :class="{
                                    '!text-primary': currentId === item.id
                                }"
                            >
                                {{ item.title }}
                            </div>
                            <div
                                v-if="item.tags"
                                class="mt-[4px] text-tx-secondary"
                            >
                                {{ item.tags }}
                            </div>
                            <div class="mt-[4px] text-tx-secondary">
                                {{ transTime(item.duration) }}
                            </div>
                        </div>
                    </div>

                    <div class="flex flex-col items-end">
                        <div class="text-tx-secondary">
                            <el-tooltip
                                v-if="item.share_status === 0"
                                effect="dark"
                                placement="top"
                                content="审核中: 审核通过后方可在广场中展示~">
                                <el-tag type="warning">分享审核中</el-tag>
                            </el-tooltip>
                            <el-tooltip
                                v-if="item.share_status === 2"
                                effect="dark"
                                placement="top"
                                :content="'分享被拒绝: '+item.share_result">
                                <el-tag type="danger">分享被拒绝</el-tag>
                            </el-tooltip>
                            <span class="ml-2">{{ item.create_time }}</span>
                        </div>
                        <div class="flex items-center gap-4 mt-[25px]">
                            <el-tooltip
                                v-if="item.audio_url"
                                effect="dark"
                                content="下载"
                                placement="bottom"
                            >
                                <div  @click.stop="handleDownload(item.audio_url, item.title)">
                                    <Icon
                                        class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                        name="el-icon-Download"
                                        size="18"
                                        color="#556477"
                                    />
                                </div>
                            </el-tooltip>
                            <el-tooltip
                                effect="dark"
                                content="分享至广场"
                                placement="bottom"
                            >
                                <div class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-[6px] box-content">
                                    <img
                                        v-if="item.share_status === -1"
                                        class="w-4 h-4 object-contain"
                                        :src="IconShare"
                                        alt="分享至广场"
                                        @click.stop="handleSquare(item.code, item.share_status)"
                                    />
                                    <img
                                        v-else
                                        class="w-4 h-4 object-contain"
                                        :src="IconLink"
                                        alt="取消分享"
                                        @click.stop="handleSquare(item.code, item.share_status)"
                                    />
                                </div>
                            </el-tooltip>
                            <el-tooltip
                                effect="dark"
                                content="删除"
                                placement="bottom"
                            >
                                <div @click.stop="handleDelete(item.code)">
                                    <Icon
                                        class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                        name="el-icon-Delete"
                                        size="18"
                                        color="#556477"
                                    />
                                </div>
                            </el-tooltip>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </el-scrollbar>
</template>

<script setup lang="ts">
import { queryLists } from '../hooks/useMusicEffect'
import { useMusicPlay, transTime } from '../hooks/useMusicPlay'
import IconLink from '~/assets/image/draw/icon_link.png'
import IconShare from '~/assets/image/draw/icon_share.png'
import musicApi from '~/api/apply/music/index'
import downloadUtil from '~/utils/download'

const props = withDefaults(
    defineProps<{
        lists?: MusicRecordResponse[];
    }>(),
    {
        lists: () => []
    }
)

const {
    playing,
    currentId,
    setMusic,
    togglePlay,
    setCurrentId
} = useMusicPlay()

/**
 * 下载音乐
 *
 * @param {string} url
 * @param {string} name
 * @author zero
 */
const handleDownload = async (url: string, name: string) => {
    try {
        const res = await $request.get(
            { url, responseType: 'blob', baseURL: '' },
            { isReturnDefaultResponse: true, apiPrefix: '' }
        )

        const blob = new Blob([res._data], {
            type: res.headers.get('Content-Type')
        })
        const link = window.URL.createObjectURL(blob)
        downloadUtil.file(link, name)
    } catch (error) {
        feedback.msgError('音乐下载失败: ' + error)
    }
}

/**
 * 处理删除
 *
 * @param {string} code
 * @author zero
 */
const handleDelete = async (code: string) => {
    await feedback.confirm('确认要删除吗？')
        .then(async () => {
            await musicApi.delete(code)
            await queryLists()
            feedback.msgSuccess('删除成功')
        }).catch(() => {})
}

/**
 * 广场公开
 *
 * @param {string} code
 * @param {number} share_status
 * @author zero
 */
const handleSquare = async (code: string, share_status: number) => {
    if (share_status !== -1) {
        feedback.confirm('您确定要取消广场分享吗?')
            .then(async () => {
                await musicApi.square(code)
                await queryLists()
                feedback.msgSuccess('取消成功')
            }).catch(() => {})
    } else {
        feedback.confirm('您确定要公开至广场吗?')
            .then(async () => {
                await musicApi.square(code)
                await queryLists()
                feedback.msgSuccess('公开成功')
            }).catch(() => {})
    }
}

/**
 * 选择播放
 *
 * @param item
 * @author zero
 */
const selectMusic = (item: any) => {
    if (item.id === currentId.value) {
        togglePlay()
        return
    }
    item.status === 2 && setCurrentId(item.id)
}

watch(
    () => props.lists,
    (value) => {
        setMusic(value)
    }, { immediate: true }
)
</script>
